package com.maori.languageapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.consts.UrlContant;
import com.maori.languageapp.database.DatabaseHelper;
import com.maori.languageapp.service.Maori_Loading_Splash;
import com.maori.languageapp.usermanager.Languageapp_Register_New_User;
import com.maori.languageapp.usermanager.Languageapp_Reset_User_Pass;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class Maori_UserLoginActivity extends Activity {
	Button UserLoginBtn, btnfogetpass, registernewuser;
	EditText etmaoriusername, etmaoripassword;
	ProgressDialog mProgressDialog;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String mainUrl;
	InputStream is = null;
	StringBuilder sb = null;
	String result;
	JSONArray jArray;
	JSONArray jsonarray;
	int loginState = 0;
	String LastDownloadUpdateTime;
	private SQLiteDatabase mydb;
	DatabaseHelper db;
	String UserArray, LanguageArray, CategoryArray, DialectArray, MediaArray,
			ContentTypeArray, WordsArray;
	String Remember = "0";
	CheckBox checkBox;
	ArrayList<HashMap<String, String>> arraylist;
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	private static final String TAG = null;
	// Master Tables
	private String USER_TABLE = "User";
	private String CONTENTTYPE_TABLE = "Content_type";
	private String DIALACT_TABLE = "Dialact";
	private String LANGUAGE_TABLE = "Language";
	private String MEDIA_TABLE = "Media";
	private String NODECATEGORY_TABLE = "Node_Category";
	private String PHRASE_TABLE = "Phrase";
	private String SONG_TABLE = "Song";
	private String STORY_TABLE = "Story";
	private String WORD_TABLE = "Word";
	private String IDIOM_TABLE = "Idiom";

	String UID;

	private Dialog mSplashDialog;;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// setContentView(R.layout.maori_login);
		setContentView(R.layout.maori_login);

		db = new DatabaseHelper(this);
		db.getWritableDatabase();
		showSplashScreen();
		mainUrl = UrlContant.UserLogin;
		UserLoginBtn = (Button) findViewById(R.id.maoriloginbutton);
		etmaoriusername = (EditText) findViewById(R.id.etmaoriusername);
		etmaoripassword = (EditText) findViewById(R.id.etmaoripassword);
		checkBox = (CheckBox) findViewById(R.id.rememberme);
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkCurrentUser = null;
		try {
			String querySelectDebtor = "SELECT * FROM User Where Activate = '1' AND Remember = '1'";
			checkCurrentUser = mydb.rawQuery(querySelectDebtor, null);
		} catch (Exception e) {
		}

		if (checkCurrentUser != null) {
			if (checkCurrentUser.getCount() > 0) {
				while (checkCurrentUser.moveToNext()) {
					String email = checkCurrentUser.getString(4).trim();
					String password = checkCurrentUser.getString(6).trim();
					etmaoriusername.setText(email);
					etmaoripassword.setText(password);
					Remember = "1";
					checkBox.isChecked();
				}
			} else {
				Remember = "0";
			}
		}

		mydb.close();

		checkBox.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (((CheckBox) v).isChecked()) {
					Log.e("TAG", "CHECK BOX CHECKED!!");
					Remember = "1";
				} else {
					Log.e("TAG", "CHECK BOX UNCHECKED!!");
					Remember = "0";
				}
			}
		});

		btnfogetpass = (Button) findViewById(R.id.btnfogetpass);
		registernewuser = (Button) findViewById(R.id.registernewuser);
		registernewuser.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intentDirectLog = new Intent(getBaseContext(),
						Languageapp_Register_New_User.class);
				/*
				 * intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				 * intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				 */
				startActivity(intentDirectLog);
				// finish();
				return;
			}
		});

		btnfogetpass.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intentDirectLog = new Intent(getBaseContext(),
						Languageapp_Reset_User_Pass.class);
				startActivity(intentDirectLog);
				// finish();
				return;
			}
		});

		UserLoginBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				String CurrentUser = etmaoriusername.getText().toString()
						.trim();
				mydb = openOrCreateDatabase(DATABASE_NAME,
						Context.MODE_PRIVATE, null);
				Cursor curSelectUser = null;
				try {
					String querySelectDebtor = "SELECT * FROM User Where email = '"
							+ CurrentUser + "'";
					curSelectUser = mydb.rawQuery(querySelectDebtor, null);
				} catch (Exception e) {
				}
				// Reset Active

				if (curSelectUser != null) {
					if (curSelectUser.getCount() > 0) {
						while (curSelectUser.moveToNext()) {
							String email = curSelectUser.getString(4).trim();
							String password = curSelectUser.getString(6).trim();
							String CurrentPass = etmaoripassword.getText()
									.toString().trim();

							if (email.equals(CurrentUser)
									&& password.equals(CurrentPass)) {
								ContentValues userUpdate = new ContentValues();
								userUpdate.put("Remember", Remember);
								userUpdate.put("Activate", "1");
								userUpdate.put("last_logedIn",
										getCurrentTimeString().toString());
								Log.v("Time", "Update "
										+ getCurrentTimeString().toString());
								mydb.update(USER_TABLE, userUpdate, "email ='" + email.trim() + "'", null);
								
								new updateUserLoginDetails().execute();
							} else {

							}

						}
					}

					else {

						ContentValues userUpdatenew = new ContentValues();
						userUpdatenew.put("Remember", "0");
						userUpdatenew.put("Activate", "0");
						userUpdatenew.put("last_logedIn",
								getCurrentTimeString().toString());
						mydb.update(USER_TABLE, userUpdatenew, "Activate ='1'",
								null);
						new sendingUserLoginDetails().execute();
					}
				} else {
					ContentValues userUpdatenew = new ContentValues();
					userUpdatenew.put("Remember", "0");
					userUpdatenew.put("Activate", "0");
					userUpdatenew.put("last_logedIn", getCurrentTimeString()
							.toString());
					mydb.update(USER_TABLE, userUpdatenew, "Activate ='1'",
							null);
					new sendingUserLoginDetails().execute();
				}

			}
		});
	}
	
	private class updateUserLoginDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairsCount = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/userRecordsCounter.php");
				JSONObject json = new JSONObject();
				json.put("record1", etmaoriusername.getText().toString());
				json.put("record2", "0");
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "UPDATEUSER :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsCount));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						arraylist = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							for (int i = 0; i < jsonarray.length(); i++) {
								JSONObject c = jsonarray.getJSONObject(i);
								String currentUID = c.getString("currentUID");
								 
								 try{
										ContentValues userUpdate = new ContentValues();
										userUpdate.put("BookmarkCount", c.getString("TotMyBMRecords"));
										userUpdate.put("MyRecordsCount", c.getString("TotMyRecords"));
										userUpdate.put("MID", c.getString("userImage").trim());
										mydb.update(USER_TABLE, userUpdate, "email ='" + currentUID.trim() + "'", null);
											
									}
									catch(Exception e){
										
									}
							}
						}
						catch(Exception e){	
						}
					}
					else{
						Log.e("REQUEST :", "XXXXXX Result :" + result);
					}

				}

			} catch (Exception e) {

			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void args) {
			Intent intentDirectLog = new Intent(getBaseContext(),Maori_MainActivity.class);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentDirectLog);
			finish();
			return;
		}
	}
	
	
	

	private class sendingUserLoginDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(Maori_UserLoginActivity.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Login");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing Login....");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		Handler alertHandler = new Handler() {

		};

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(mainUrl);
				JSONObject json = new JSONObject();
				json.put("record1", etmaoriusername.getText().toString());
				json.put("record2", etmaoripassword.getText().toString());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "Login request :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						Log.e("REQUEST :", "Login Result :" + result);
						jArray = new JSONArray(result);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							json_data = jArray.getJSONObject(i);

							String login_state = json_data
									.getString("login_state");
							Log.e("login_state 1 :", "login_state :"
									+ login_state);
							if (login_state.equals("false")) {
								loginState = 1;
							} else {
								loginState = 2;

							}
							Log.e("loginState 2 :", "loginState :" + loginState);
							saveUserDetails();
						}
					}

				}

			} catch (Exception e) {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			if (loginState == 2) {
				syncServerData();

			} else if (loginState == 1) {
				final AlertDialog alertDialog = new AlertDialog.Builder(
						Maori_UserLoginActivity.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("INVLID LOGIN");
				// Setting Dialog Message
				alertDialog
						.setMessage("Please Enter Correct Username and Password");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;
			}
		}
	}

	public void syncServerData() {
		// TODO Auto-generated method stub
		new DownloadLanguageDetails().execute();
	}

	// Save Loged In Users Details
	public void saveUserDetails() {
		// TODO Auto-generated method stub
		try {
			UserArray = result.replace("[{\"login_state\":{", "[{");
			UserArray = UserArray.replace("}}]", "}]");
			Log.e("UserArray :", "UserArray :" + UserArray);
			jArray = new JSONArray(UserArray);
			JSONObject json_data = null;
			for (int i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				String first_name = json_data.getString("first_name");
				String last_name = json_data.getString("last_name");
				String tribe = json_data.getString("tribe");
				String email = json_data.getString("email");
				String username = json_data.getString("username");
				String password = json_data.getString("password");
				String role = json_data.getString("role");
				String user_created = json_data.getString("user_created");
				String last_logedIn = json_data.getString("last_logedIn");
				String status = json_data.getString("status");
				UID = json_data.getString("UID");
				String MID = json_data.getString("MID");

				mydb = openOrCreateDatabase(DATABASE_NAME,
						Context.MODE_PRIVATE, null);
				ContentValues enterUserInfo = new ContentValues();
				Cursor readUserDetails = null;
				try {
					readUserDetails = mydb.query(USER_TABLE, null, "UID ='"
							+ UID.trim() + "'", null, null, null, null);
				} catch (Exception e) {
					Log.e("Exception :", "Exception 1 :" + e);
				}
				Log.e("Exception :",
						"readUserDetails 1 :" + readUserDetails.getCount());

				if (readUserDetails != null) {
					if (readUserDetails.getCount() >= 1) {
						while (readUserDetails.moveToNext()) {
							Log.e("Excisting :", "Excisting");
							LastDownloadUpdateTime = readUserDetails
									.getString(13);
							// LastDownloadUpdateTime = "1900-01-01 12:00:00";
							Log.e("Excisting User :", "Excisting User 1 :"
									+ LastDownloadUpdateTime);
							ContentValues userUpdate = new ContentValues();
							userUpdate.put("LatestDownload",
									getCurrentTimeString().toString());
							userUpdate.put("last_logedIn",
									getCurrentTimeString().toString());
							mydb.update(USER_TABLE, userUpdate,
									"UID ='" + UID.trim() + "'", null);
						}

					} else {
						Log.e("new :", "new");
						enterUserInfo.put("first_name", first_name.trim());
						enterUserInfo.put("last_name", last_name.trim());
						enterUserInfo.put("tribe", tribe.trim());
						enterUserInfo.put("email", email.trim());
						enterUserInfo.put("username", username.trim());
						enterUserInfo.put("password", password.trim());
						enterUserInfo.put("role", role.trim());
						enterUserInfo.put("user_created", user_created.trim());
						enterUserInfo.put("last_logedIn", last_logedIn.trim());
						enterUserInfo.put("status", status.trim());
						enterUserInfo.put("UID", UID.trim());
						enterUserInfo.put("MID", MID.trim());
						enterUserInfo.put("LatestDownload",
								getCurrentTimeString().toString());
						enterUserInfo.put("Activate", "1");
						enterUserInfo.put("Remember", Remember);
						enterUserInfo.put("BookmarkCount", "0");
						enterUserInfo.put("MyRecordsCount", "0");
						LastDownloadUpdateTime = "1900-01-01 12:00:00";
						mydb.insert(USER_TABLE, null, enterUserInfo);
						readUserDetails.close();
						mydb.close();
					}
				}
			}
		} catch (Exception e) {
			// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			Log.e("new  Exception:", "new Exception :" + e);
		}

	}

	// Download available details
	private class DownloadLanguageDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(Maori_UserLoginActivity.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading");
			// Set progressdialog message
			mProgressDialog.setMessage("Processing Downloading....");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			// *****Download and Update Language Details*****
			ArrayList<NameValuePair> nameValuePairsLanguage = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);

				HttpPost httppost = new HttpPost(UrlContant.LanguageURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsLanguage));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				LanguageArray = sb.toString();

				jArray = new JSONArray(LanguageArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String LID = json_data.getString("LID");
					String Language = json_data.getString("Language");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterLanguageInfo = new ContentValues();
					// Check Previous Language
					Cursor readLanguageDetails = null;
					try {
						readLanguageDetails = mydb.query(LANGUAGE_TABLE, null,
								"LID ='" + LID.trim() + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (readLanguageDetails != null) {
						if (readLanguageDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Language");
						} else {
							enterLanguageInfo.put("LID", LID.trim());
							enterLanguageInfo.put("Language", Language.trim());
							mydb.insert(LANGUAGE_TABLE, null, enterLanguageInfo);
							readLanguageDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Language Download Complete------

			// *****Download and Update Category Details*****
			ArrayList<NameValuePair> nameValuePairsCategory = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.CategoryURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsCategory));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				CategoryArray = sb.toString();

				jArray = new JSONArray(CategoryArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String node_category = json_data.getString("node_category");
					String NCMID = json_data.getString("NCMID");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterLanguageInfo = new ContentValues();
					// Check Previous Language
					Cursor readLanguageDetails = null;
					try {
						readLanguageDetails = mydb.query(NODECATEGORY_TABLE,
								null, "NCMID ='" + NCMID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readLanguageDetails != null) {
						if (readLanguageDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Category");
						} else {
							enterLanguageInfo.put("node_cat_id", NCMID.trim());
							enterLanguageInfo.put("node_category",
									node_category.trim());
							enterLanguageInfo.put("NCMID", NCMID.trim());
							mydb.insert(NODECATEGORY_TABLE, null,
									enterLanguageInfo);
							readLanguageDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Category Download Complete------

			// *****Download and Update Dialect Details*****
			ArrayList<NameValuePair> nameValuePairsDialect = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.DialectURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsDialect));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				DialectArray = sb.toString();

				jArray = new JSONArray(DialectArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String dialact_id = json_data.getString("dialact_id");
					String dialact = json_data.getString("dialact");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterDialectInfo = new ContentValues();
					// Check Previous Language
					Cursor readDialectDetails = null;
					try {
						readDialectDetails = mydb.query(DIALACT_TABLE, null,
								"dialact_id ='" + dialact_id.trim() + "'",
								null, null, null, null);
					} catch (Exception e) {
					}
					if (readDialectDetails != null) {
						if (readDialectDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Dialect");
						} else {
							enterDialectInfo.put("dialact_id",
									dialact_id.trim());
							enterDialectInfo.put("dialact", dialact.trim());
							mydb.insert(DIALACT_TABLE, null, enterDialectInfo);
							readDialectDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}
			// --------Dialect Download Complete------

			// *****Download and Update Media Details*****
			ArrayList<NameValuePair> nameValuePairsMedia = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.MediaURL);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsMedia));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				MediaArray = sb.toString();

				jArray = new JSONArray(MediaArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String MID = json_data.getString("MID");
					String media_type = json_data.getString("media_type");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterMediaInfo = new ContentValues();
					// Check Previous Language
					Cursor readMediaDetails = null;
					try {
						readMediaDetails = mydb.query(MEDIA_TABLE, null,
								"MID ='" + MID.trim() + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (readMediaDetails != null) {
						if (readMediaDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Media");
						} else {
							enterMediaInfo.put("MID", MID.trim());
							enterMediaInfo.put("media_type", media_type.trim());
							mydb.insert(MEDIA_TABLE, null, enterMediaInfo);
							readMediaDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}

			// --------Dialect Download Complete------

			// *****Download and Update Content Type Details*****
			ArrayList<NameValuePair> nameValuePairsContentType = new ArrayList<NameValuePair>();
			try {
				HttpParams httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.ContentTypeURL);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsContentType));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				ContentTypeArray = sb.toString();

				jArray = new JSONArray(ContentTypeArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String content_type_id = json_data
							.getString("content_type_id");
					String content = json_data.getString("content");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterContentTypeInfo = new ContentValues();
					// Check Previous Language
					Cursor readContentTypeDetails = null;
					try {
						readContentTypeDetails = mydb.query(CONTENTTYPE_TABLE,
								null,
								"content_type_id ='" + content_type_id.trim()
										+ "'", null, null, null, null);
					} catch (Exception e) {
					}
					if (readContentTypeDetails != null) {
						if (readContentTypeDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Content Type");
						} else {
							enterContentTypeInfo.put("content_type_id",
									content_type_id.trim());
							enterContentTypeInfo.put("content", content.trim());
							mydb.insert(CONTENTTYPE_TABLE, null,
									enterContentTypeInfo);
							readContentTypeDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {

			}

			// --------Content Type Download Complete------

			// *****Download and Update Words Details*****

			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.WordsURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE WORDS :", "Response **** :" + WordsArray);

				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					// [{"LID":"1","NID":"1","word":"parehe","NID_ID":"1","node_timestamp":"2014-02-10 18:18:17"},
					String WordID = json_data.getString("WordID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID_ID");
					String word = json_data.getString("word");
					String otherwords = json_data.getString("otherwords");
					String activeState = json_data.getString("node_active_a");
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(WORD_TABLE, null,
								"WordID ='" + WordID.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Word");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("WordID", WordID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("word", word.trim());
							wordsUpdate.put("otherwords", otherwords.trim());
							wordsUpdate.put("activeState", activeState.trim());

							mydb.update(WORD_TABLE, wordsUpdate, "WordID ='"
									+ WordID.trim() + "'", null);
						} else {
							enterWordInfo.put("WordID", WordID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("word", word.trim());
							enterWordInfo.put("Otherwords", otherwords.trim());
							enterWordInfo
									.put("activeState", activeState.trim());
							mydb.insert(WORD_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Idiom Details*****

			ArrayList<NameValuePair> nameValuePairsIdiom = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.IdiomURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST IDIOM :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsIdiom));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();

				Log.e("RESPONSE Idiom :", "Response **** :" + WordsArray);

				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					// [{"LID":"1","NID":"1","word":"parehe","NID_ID":"1","node_timestamp":"2014-02-10 18:18:17"},
					String IdiomID = json_data.getString("IdiomID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID_ID");
					String Idiom = json_data.getString("Idiom");
					String Otheridioms = json_data.getString("Otheridioms");
					String activeState = json_data.getString("$node_active_a");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(IDIOM_TABLE, null,
								"IdiomID ='" + IdiomID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Word");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("IdiomID", IdiomID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("Idiom", Idiom.trim());
							wordsUpdate.put("Otheridioms", Otheridioms.trim());
							wordsUpdate.put("activeState", activeState.trim());
							mydb.update(IDIOM_TABLE, wordsUpdate, "WordID ='"
									+ IdiomID.trim() + "'", null);
						} else {
							enterWordInfo.put("IdiomID", IdiomID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("Idiom", Idiom.trim());
							enterWordInfo
									.put("Otheridioms", Otheridioms.trim());
							enterWordInfo
									.put("activeState", activeState.trim());
							mydb.insert(IDIOM_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Songs Details*****

			ArrayList<NameValuePair> nameValuePairsSongs = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.SongsURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST SONGS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsSongs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE Songs :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String SongID = json_data.getString("SongID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String song_title = json_data.getString("song_title");
					String song_content = json_data.getString("song_content");
					String other_song_title = json_data
							.getString("other_song_title");
					String other_song_content = json_data
							.getString("other_song_content");
					String activeState = json_data.getString("node_active_a");
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(SONG_TABLE, null,
								"SongID ='" + SongID.trim() + "'", null, null,
								null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Song");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("SongID", SongID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("song_title", song_title.trim());
							wordsUpdate
									.put("song_content", song_content.trim());
							wordsUpdate.put("other_song_title",
									other_song_title.trim());
							wordsUpdate.put("other_song_content",
									other_song_content.trim());
							wordsUpdate.put("activeState", activeState.trim());
							mydb.update(SONG_TABLE, wordsUpdate, "SongID ='"
									+ SongID.trim() + "'", null);
						} else {
							enterWordInfo.put("SongID", SongID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("song_title", song_title.trim());
							enterWordInfo.put("song_content",
									song_content.trim());
							enterWordInfo.put("other_song_title",
									other_song_title.trim());
							enterWordInfo.put("other_song_content",
									other_song_content.trim());
							enterWordInfo
									.put("activeState", activeState.trim());
							mydb.insert(SONG_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Phrase Details*****

			ArrayList<NameValuePair> nameValuePairsPhrase = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.PhraseURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(
						nameValuePairsPhrase));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE Phrase :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String PhraseID = json_data.getString("PhraseID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String Phrase = json_data.getString("Phrase");
					String OtherPhrase = json_data.getString("OtherPhrase");
					String activeState = json_data.getString("node_active_a");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(PHRASE_TABLE, null,
								"PhraseID ='" + PhraseID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting Phrase");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("PhraseID", PhraseID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("Phrase", Phrase.trim());
							wordsUpdate.put("OtherPhrase", OtherPhrase.trim());
							wordsUpdate.put("activeState", activeState.trim());

							mydb.update(PHRASE_TABLE, wordsUpdate,
									"PhraseID ='" + PhraseID.trim() + "'", null);
						} else {
							enterWordInfo.put("PhraseID", PhraseID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo.put("Phrase", Phrase.trim());
							enterWordInfo
									.put("OtherPhrase", OtherPhrase.trim());
							enterWordInfo
									.put("activeState", activeState.trim());

							mydb.insert(PHRASE_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			// --------Content Type Download Complete------

			// *****Download and Update Story Details*****

			ArrayList<NameValuePair> nameValuePairsStory = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost(UrlContant.StoryURL);
				JSONObject json = new JSONObject();
				json.put("record1", LastDownloadUpdateTime.trim());
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST WORDS :", "request **** :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsStory));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();

				is = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "iso-8859-1"), 8);
				sb = new StringBuilder();
				sb.append(reader.readLine() + "\n");
				String line = "0";
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				WordsArray = sb.toString();
				Log.e("RESPONSE STORY :", "Response **** :" + WordsArray);
				jArray = new JSONArray(WordsArray);
				JSONObject json_data = null;
				for (int i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					String StoryID = json_data.getString("StoryID");
					String LID = json_data.getString("LID");
					String NID = json_data.getString("NID");
					String story_title = json_data.getString("story_title");
					String story_content = json_data.getString("story_content");
					String other_story_title = json_data
							.getString("other_story_title");
					String other_story_content = json_data
							.getString("other_story_content");
					String activeState = json_data.getString("node_active_a");

					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);
					ContentValues enterWordInfo = new ContentValues();
					// Check Previous Language
					Cursor readWordDetails = null;
					try {
						readWordDetails = mydb.query(STORY_TABLE, null,
								"StoryID ='" + StoryID.trim() + "'", null,
								null, null, null);
					} catch (Exception e) {
					}
					if (readWordDetails != null) {
						if (readWordDetails.getCount() >= 1) {
							Log.v(TAG, "Excisting StoryID");
							ContentValues wordsUpdate = new ContentValues();
							wordsUpdate.put("StoryID", StoryID.trim());
							wordsUpdate.put("LID", LID.trim());
							wordsUpdate.put("NID", NID.trim());
							wordsUpdate.put("story_title", story_title.trim());
							wordsUpdate.put("story_content",
									story_content.trim());
							wordsUpdate.put("other_story_title",
									other_story_title.trim());
							wordsUpdate.put("other_story_content",
									other_story_content.trim());
							wordsUpdate.put("activeState", activeState.trim());

							mydb.update(STORY_TABLE, wordsUpdate, "StoryID ='"
									+ StoryID.trim() + "'", null);
						} else {
							enterWordInfo.put("StoryID", StoryID.trim());
							enterWordInfo.put("LID", LID.trim());
							enterWordInfo.put("NID", NID.trim());
							enterWordInfo
									.put("story_title", story_title.trim());
							enterWordInfo.put("story_content",
									story_content.trim());
							enterWordInfo.put("other_story_title",
									other_story_title.trim());
							enterWordInfo.put("other_story_content",
									other_story_content.trim());
							enterWordInfo
									.put("activeState", activeState.trim());
							mydb.insert(STORY_TABLE, null, enterWordInfo);
							readWordDetails.close();
							mydb.close();
						}
					}

				}

			} catch (Exception e) {
				Log.v(TAG, "Exception e :" + e);
			}

			ArrayList<NameValuePair> nameValuePairsCount = new ArrayList<NameValuePair>();
			try {
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				HttpPost httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/userRecordsCounter.php");
				JSONObject json = new JSONObject();
				json.put("record1", etmaoriusername.getText().toString());
				json.put("record2", "0");
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.e("REQUEST :", "UPDATEUSER :" + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsCount));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {
						arraylist = new ArrayList<HashMap<String, String>>();
						try {
							JSONObject jsonObj = new JSONObject(result);
							jsonarray = jsonObj.getJSONArray("posts");
							for (int i = 0; i < jsonarray.length(); i++) {
								JSONObject c = jsonarray.getJSONObject(i);
								String currentUID = c.getString("currentUID");
								 
								 try{
										ContentValues userUpdate = new ContentValues();
										userUpdate.put("BookmarkCount", c.getString("TotMyBMRecords"));
										userUpdate.put("MyRecordsCount", c.getString("TotMyRecords"));
										userUpdate.put("MID", c.getString("userImage").trim());
										mydb.update(USER_TABLE, userUpdate, "email ='" + currentUID.trim() + "'", null);
											
									}
									catch(Exception e){
										
									}
							}
						}
						catch(Exception e){	
						}
					}
					else{
						Log.e("REQUEST :", "XXXXXX Result :" + result);
					}

				}

			} catch (Exception e) {

			}

			// --------Content Type Download Complete------
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			Intent intentDirectLog = new Intent(getBaseContext(),
					Maori_MainActivity.class);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentDirectLog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intentDirectLog);
			finish();
			return;
		}

	}

	public void showSplashScreen() {
		mSplashDialog = new Dialog(this, R.style.SplashScreen);
		mSplashDialog.setContentView(R.layout.maori_loading);
		mSplashDialog.setCancelable(false);
		mSplashDialog.show();

		final Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				removeSplashScreen();
			}
		}, 3000);
	}

	public void removeSplashScreen() {
		if (mSplashDialog != null) {
			mSplashDialog.dismiss();
			mSplashDialog = null;
		}
	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

}
